package com.example.test.dialogfactory;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.coordinatorlayout.widget.CoordinatorLayout.Behavior;
import androidx.core.view.ViewCompat;
import androidx.recyclerview.widget.RecyclerView;

public class BottomTabBehavior extends Behavior< TextView > {

    // 记录移动了多少距离
    private int mMoveY;

    public BottomTabBehavior() {}

    public BottomTabBehavior( Context context, AttributeSet attrs ) {

        super( context, attrs );
    }

    @Override
    public boolean layoutDependsOn(
        @NonNull CoordinatorLayout parent, @NonNull TextView child, @NonNull View dependency ) {

        /* 依赖recyclerView */
        return dependency instanceof RecyclerView;
    }

    @Override
    public boolean onDependentViewChanged(
        @NonNull CoordinatorLayout parent, @NonNull TextView child, @NonNull View dependency ) {

        /* 当recyclerView位置变化时回调 */
        return super.onDependentViewChanged( parent, child, dependency );
    }

    @Override
    public boolean onStartNestedScroll(
        @NonNull CoordinatorLayout coordinatorLayout, @NonNull TextView child,
        @NonNull View directTargetChild, @NonNull View target, int axes, int type ) {

        /* 当竖直滑动时捕获滑动 */
        return (axes & ViewCompat.SCROLL_AXIS_VERTICAL) != 0;
    }

    @Override
    public void onNestedPreScroll(
        @NonNull CoordinatorLayout coordinatorLayout, @NonNull TextView child,
        @NonNull View target, int dx, int dy, @NonNull int[] consumed, int type ) {

        super.onNestedPreScroll( coordinatorLayout, child, target, dx, dy, consumed, type );

        /* 响应recyclerView滑动 */
        int height = child.getHeight();
        if ( mMoveY + dy > height ) {
            dy = height - mMoveY;
        }

        if ( mMoveY + dy < 0 ) {
            dy = -mMoveY;
        }

        if ( dy != 0 ) {

            child.setY( child.getY() + dy );
            mMoveY += dy;
        }
    }
}